import { tophubAttachmentPreview } from '@/services/api/api-tophub-attachment';
import { listTophubOperateState } from '@/services/api/api-tophub-operate';

import { DownloadOutlined } from '@ant-design/icons';
import { ActionType, DrawerForm, ProCard } from '@ant-design/pro-components';
import { useAccess } from '@umijs/max';
import {
  Alert,
  Button,
  Descriptions,
  Flex,
  Image,
  message,
  Spin,
  Tag,
  Timeline,
  Typography,
  Upload,
  UploadFile,
} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
interface DetailsOperateStateProps {
  data: TophubOperateData.OperatePage | undefined;
  onRefurbish: () => void;
}

const DetailsOperateState: React.FC<DetailsOperateStateProps> = ({ data, onRefurbish }) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();

  const [open, setOpenState] = useState(false);

  const [states, setStatesState] = useState<any[]>([]);

  const [selectStateId, setSelectStatesIdState] = useState<number>(0);

  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewData, setPreviewData] = useState<{
    id: string;
    name: string;
    mimeType: string;
    url?: string;
  }>();
  const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
  const [previewLoading, setPreviewLoading] = useState(true);

  const getWindowSize = () => ({
    innerHeight: window.innerHeight,
    innerWidth: window.innerWidth,
  });
  const [windowSize, setWindowSize] = useState(getWindowSize());
  const handleResize = () => {
    setWindowSize(getWindowSize());
  };
  useEffect(() => {
    // 监听
    window.addEventListener('resize', handleResize);
    // 销毁
    return () => window.removeEventListener('resize', handleResize);
  });

  const iframeRef = useRef(null);

  /**
   * 加载 选题计划详情
   * @param key
   */
  const loadSaveInitTophubRecord = async () => {
    try {
      const response = await listTophubOperateState({
        id: data?.id,
      });

      if (response.code == 0) {
        setStatesState(
          response.data.map((item, index) => {
            let color = 'blue';

            let stateName = '';

            if (item.state == 1) {
              color = 'blue';
              stateName = '申请';
            } else if (item.state == 2) {
              color = 'red';
              stateName = '退回';
            } else if (item.state == 3) {
              color = 'green';
              stateName = '发布';
            }

            return {
              color: color,
              children: (
                <>
                  <div>
                    <Tag color={color}>{stateName}</Tag>
                    <a
                      key={item.id}
                      onClick={() => {
                        setSelectStatesIdState(index);
                      }}
                    >
                      {item.createdOrganizationName}
                    </a>
                  </div>
                  <div>{item.createdTime}</div>
                  <div>{item.createdAccountName}</div>
                  {item?.content && (
                    <Typography.Paragraph>
                      <blockquote>{item?.content}</blockquote>
                    </Typography.Paragraph>
                  )}
                </>
              ),
              ...item,
            };
          }),
        );
        setLoading(false);
      }
    } catch (error) {}
  };

  return (
    <DrawerForm
      title="审核流程"
      trigger={<a>审核流程</a>}
      autoFocusFirstInput
      drawerProps={{
        destroyOnClose: true,
        width: 750,
      }}
      open={open}
      onOpenChange={async (visible) => {
        setOpenState(visible);
        if (visible) {
          loadSaveInitTophubRecord();
        } else {
          onRefurbish();
        }
      }}
      submitter={false}
      onFinish={async (values) => {}}
    >
      <ProCard split="vertical" ghost>
        <ProCard
          loading={states?.length == 0}
          colSpan="40%"
          bodyStyle={{
            paddingTop: 10,
            paddingLeft: 5,
          }}
        >
          <Timeline items={states} />
        </ProCard>
        <ProCard loading={states?.length == 0} headerBordered>
          <Typography.Title level={5}>{data?.hotName}</Typography.Title>
          <Descriptions column={2}>
            <Descriptions.Item label="账号">{data?.datahubSourceName}</Descriptions.Item>
            <Descriptions.Item label="媒体">{data?.datahubLevelName}</Descriptions.Item>
            <Descriptions.Item label="平台">
              {data?.hotType == 1 ? '微博' : data?.hotType == 2 ? '抖音' : '头条'}
            </Descriptions.Item>
            <Descriptions.Item label="范围">
              {data?.hotIsCity == 0 ? '全国' : '重庆'}
            </Descriptions.Item>
            <Descriptions.Item label="创建人">{data?.createdAccountName}</Descriptions.Item>
          </Descriptions>
          <Typography.Paragraph>
            <blockquote>{states[selectStateId]?.remarks}</blockquote>
          </Typography.Paragraph>
          {states[selectStateId]?.attachments && (
            <div
              style={{
                marginTop: 10,
              }}
            >
              <Flex justify="space-between" align="center">
                <span>附件：</span>
                <Button
                  type="primary"
                  key="import"
                  size="small"
                  icon={<DownloadOutlined />}
                  onClick={() => {
                    states[selectStateId]?.attachments?.forEach(function (item) {
                      window.open(item.content, '_blank');
                    });
                  }}
                >
                  全部下载
                </Button>
              </Flex>
              <Upload
                listType="picture"
                multiple
                fileList={states[selectStateId]?.attachments?.map((item) => {
                  return {
                    uid: item.id,
                    name: (
                      <a
                        style={{
                          width: '280px',
                        }}
                      >
                        <a
                          style={{
                            display: 'block',
                            width: '190px',
                            textOverflow: 'ellipsis',
                            overflow: 'hidden',
                            wordBreak: 'break-all',
                            whiteSpace: 'nowrap',
                          }}
                        >
                          {item.name}
                        </a>
                      </a>
                    ),
                    url: item.content,
                    mimeType: item.mimeType,
                    status: 'done',
                  };
                })}
                showUploadList={{
                  downloadIcon: (
                    <div style={{ marginLeft: '-100px', padding: '17px 0', marginTop: '-15px' }}>
                      <DownloadOutlined
                        style={{
                          marginRight: '10px',
                        }}
                      />
                      点击下载
                    </div>
                  ),
                  showRemoveIcon: false,
                  showDownloadIcon: true,
                }}
                onPreview={async (file: UploadFile) => {
                  setPreviewData({
                    id: file.uid,
                    name: file.name,
                    mimeType: file.mimeType,
                    url: encodeURI(file.url),
                  });
                  setPreviewOpen(true);
                }}
              />
              <DrawerForm
                title={previewData?.name}
                drawerProps={{
                  width: 900,
                  destroyOnClose: true,
                }}
                open={previewOpen}
                onOpenChange={async (visible) => {
                  if (visible) {
                    if (
                      previewData?.mimeType !== null &&
                      previewData?.mimeType?.indexOf('image') > -1
                    ) {
                      //图片预览
                    } else {
                      setPreviewLoading(true);

                      const response = await tophubAttachmentPreview({
                        id: previewData?.id,
                      });

                      if (response.code === 0) {
                        setPreviewOnlineUrl(response.data);
                      } else {
                        message.error('暂时无法预览');
                        setPreviewLoading(false);
                      }
                    }
                  } else {
                    setPreviewOpen(false);
                    setPreviewData(undefined);
                    setPreviewOnlineUrl(undefined);
                  }
                }}
                submitter={{
                  searchConfig: {
                    submitText: '下载',
                  },
                }}
                onFinish={async (values) => {
                  window.open(previewData?.url, '_blank');
                }}
              >
                <Alert
                  style={{
                    marginBottom: 20,
                  }}
                  message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                  type="warning"
                  showIcon
                />
                {previewData?.mimeType !== null && previewData?.mimeType?.indexOf('image') > -1 ? (
                  <Image width="100%" src={previewData?.url} />
                ) : (
                  <Spin spinning={previewLoading}>
                    <iframe
                      ref={iframeRef}
                      src={previewOnlineUrl}
                      height={windowSize.innerHeight - 220}
                      width="100%"
                      frameBorder="0"
                      // scrolling="false"
                      allowFullScreen={true}
                      // scrolling={'no'}
                    />
                  </Spin>
                )}
              </DrawerForm>
            </div>
          )}
        </ProCard>
      </ProCard>
    </DrawerForm>
  );
};
export default DetailsOperateState;
